package i_quartz;

import java.util.List;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class JDBCQuartz {
	
	public static void main(String[] args) {
		
		startSchedule();
		//resumeJob();
	}
	
	/**
	 * 开始一个simpleSchedule()调度
	 */
	private static void startSchedule() {
		//1.创建一个JobDetail实例,指定Quqrtz
		JobDetail jobDetail = JobBuilder.newJob(JDBCJob.class)		//任务执行类
								.withIdentity("job1-1","jGroup1")	//任务名,任务组
								.build();
		
		//触发器类型
		SimpleScheduleBuilder builder = SimpleScheduleBuilder
										.repeatSecondlyForTotalCount(5);	//设置执行次数
		CronScheduleBuilder builder2 = CronScheduleBuilder.cronSchedule("0/2 * * * * ?");
		
		//2.创建trigger
		Trigger trigger = TriggerBuilder.newTrigger()
							.withIdentity("trigger1-1","tGroup1")
							.startNow()
							.withSchedule(builder2).build();
		
		try {
			//3.创建Scheduler
			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
			scheduler.start();
			
			//4.执行调度
			scheduler.scheduleJob(jobDetail, trigger);
			
			try {
				Thread.sleep(1000*30);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			//关闭调度器
			scheduler.shutdown();
			
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 从数据库中找到已经存在的job,并重新开户调度
	 */
	private static void resumeJob(){
		
		try {
			StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
			Scheduler scheduler = schedulerFactory.getScheduler();
			JobKey jobKey = new JobKey("job1-1","jGroup1");
			List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
			//SELECT TRIGGER_NAME,TRIGGER_GROUP FROM {0}TRIGGERS WHERE SCHED_NAME = {1} AND JOB_NAME = ? AND JOB_GROUP = ?
			//重新恢复在jGroup1组中,名为job1-1的job触发器运行
			if (triggers.size()>0) {
				for (Trigger trigger : triggers) {
					//根据类型判断
					if ((trigger instanceof CronTrigger) || (trigger instanceof SimpleTrigger)) {
						//恢复job运行
						scheduler.resumeJob(jobKey);
					}
				}
			}
			
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}
